package com.heima.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.heima.account.entity.Account;
import com.heima.account.entity.AccountFreeze;
import com.heima.account.service.IAccountAction;
import com.heima.account.service.IAccountFreezeService;
import com.heima.account.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountActionImpl implements IAccountAction {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountFreezeService accountFreezeService;
    @Override
    public void deduct(Integer userId, Integer money) {

        AccountFreeze accountFreeze = new AccountFreeze();
        String xid = RootContext.getXID();
        accountFreeze.setXid(xid);
        accountFreeze.setUserId(userId);
        accountFreeze.setFreezeMoney(money);
        accountFreezeService.save(accountFreeze);
        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Account::getUserId,userId);
        updateWrapper.setSql("money = money-" + money);
        accountService.update(updateWrapper);
    }

    @Override
    public boolean success(BusinessActionContext context) {

        LambdaQueryWrapper<AccountFreeze> queryWrapper = new LambdaQueryWrapper<>();
        String xid = context.getXid();
        queryWrapper.eq(AccountFreeze::getXid,xid);
        accountFreezeService.remove(queryWrapper);

        return true;
    }

    @Override
    public boolean fail(BusinessActionContext context) {

        Integer userId = (Integer) context.getActionContext("userId");
        Integer money = (Integer) context.getActionContext("money");
        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Account::getUserId,userId);
        updateWrapper.setSql("money = money+" + money);
        accountService.update(updateWrapper);

        LambdaQueryWrapper<AccountFreeze> queryWrapper = new LambdaQueryWrapper<>();
        String xid = context.getXid();
        queryWrapper.eq(AccountFreeze::getXid,xid);
        accountFreezeService.remove(queryWrapper);
        return true;
    }
}
